## @package puppettools
# This package contains the functions to generate compiled puppet catalogs for roles

import commands
import tempfile
import os
import shutil
import logging
log = logging.getLogger(__name__)

## Generate compiled puppet catalog given sitepp, confdir, and nodename
#  @param confdir Path to where all the puppet configurations are (path to the directory that contains directory modules). 
#  @param sitepp A string containing the containing the would-be site.pp file
#  @param nodename A string containing the node name, it must be defined in the sitepp file.
#  @return None if unsuccessful, a String containing the catalog if successful
def compileCatalog(confdir,sitepp,nodename,facts=None):


    vardir=tempfile.mkdtemp()

    #Write out facts
    if not facts is None:
        os.makedirs(vardir+"/yaml/facts")
        ouf=open(vardir+"/yaml/facts/"+nodename+".yaml","w")
        ouf.write(facts)
        ouf.write("\n")
        ouf.close()

    cmdstrtemplate="puppet master --vardir=%(VARDIR)s --manifest %(NODESPP)s --compile %(NODENAME)s"

    #TODO: test if confdir exists

    #write sitepp file
    (oufd, siteppfilename) = tempfile.mkstemp() 
    os.write(oufd,sitepp)
    os.write(oufd,"\n")
    os.close(oufd)

    cmdstr=cmdstrtemplate%{"NODESPP":siteppfilename,
                           "NODENAME":nodename, 
                           "VARDIR":vardir
                           }

    (status,output)=commands.getstatusoutput(cmdstr)

    log.debug("Cmdstr: %s"%cmdstr);
    log.debug("Status: %s"%status);
    log.debug("Output: %s"%output);

    #remove the temp file
    os.remove(siteppfilename)
    shutil.rmtree(vardir)

    if status!=0:
        return None

    catalogtext=output[output.find("{"):]

    return catalogtext



